package com.zglc.ms.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zglc.ms.base.constants.ResponseCodeHelper;
import com.zglc.ms.shop.controller.log.RequestLog;
import com.zglc.ms.shop.filter.JwtHelper;
import com.zglc.ms.shop.model.ShopHomeTemplateVo;
import com.zglc.ms.shop.model.ShopProduct;
import com.zglc.ms.shop.model.UserAddress;
import com.zglc.ms.shop.service.*;
import com.zglc.ms.shop.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.zglc.ms.shop.util.CommonUtils.RETURN_CODE;
import static com.zglc.ms.shop.util.CommonUtils.RETURN_DATA;

@Controller
@RequestMapping("/front")
public class ProductController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ShopProductService shopProductService;

    @Autowired
    private ShopHomeTemplateVoService shopHomeTemplateVoService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private PointService pointService;

    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    private final String SHOPPRODUCTDETAIL_CACHE_KEY = "ShopProductDetail+";

    // 获取产品详情-根据产品Id
    @RequestMapping("/product/getDetail")
    @ResponseBody
    @RequestLog
    public Map<String, Object> getProductDetailByProductId(HttpServletRequest request, @RequestParam int productId) {
        Map<String, Object> map = CommonUtils.successResponse();
        if (productId <= 0) {
            map.put(RETURN_CODE, ResponseCodeHelper.PRODUCT_ID_ERROR);
            map.put("msg", "产品Id错误");
            return map;
        }

        JSONObject result = new JSONObject();
        if (cacheManagerUtil.isExist(SHOPPRODUCTDETAIL_CACHE_KEY + productId)) {
            String cacheValue = cacheManagerUtil.jGet(SHOPPRODUCTDETAIL_CACHE_KEY + productId);
            if (!StringUtils.isEmpty(cacheValue)) {
                try {
                    result = JSONObject.parseObject(cacheManagerUtil.jGet(SHOPPRODUCTDETAIL_CACHE_KEY + productId));
                } catch (Exception e) {
                    logger.error("e = " + e.getMessage());
                }
                result = addAddress(result, request);
                map.put(RETURN_CODE, 0);
                map.put(RETURN_DATA, result);
                return map;
            }
        }

        logger.info("详情没有缓存,读取数据库");
        ShopProduct productDetail = shopProductService.getProductDetailById(productId);
        if (productDetail == null) {
            map.put(RETURN_CODE, ResponseCodeHelper.NO_PRODUCTS_BY_ID);
            map.put("msg", "该商品已下架");
            return map;
        }

        try {
            String ruleName = pointService.getRuleMap().get(productDetail.getPriceType());
            org.json.JSONObject jsonObject = new org.json.JSONObject(productDetail);
            jsonObject.put("priceName", ruleName);
            logger.debug("priceName={},json={}", ruleName,jsonObject.toString());
            String jsonResult = jsonObject.toString();
            cacheManagerUtil.jSet(SHOPPRODUCTDETAIL_CACHE_KEY + productId, jsonResult,
                    CacheManagerUtil.SHOW_VALID_TIME);
            result = addAddress(JSONObject.parseObject(jsonResult), request);

        } catch (Exception e) {
            logger.error("e = " + e.getMessage());
        }

        map.put(RETURN_CODE, ResponseCodeHelper.SUCCESS);
        map.put(RETURN_DATA, result);
        return map;
    }

    public JSONObject addAddress(JSONObject result, HttpServletRequest request) {
        try {
            Integer userId = JwtHelper.getUserId(request);
            if (userId == null) {
                result.put("isHasAddress", false);
                return result;
            }

            UserAddress userAddress = addressService.getLastestAddress(userId);
            if (userAddress == null) {
                result.put("isHasAddress", false);
            } else {
                result.put("isHasAddress", true);
                result.put("addressId", userAddress.getId());
                result.put("address", userAddress.getRemark());
                result.put("phone", userAddress.getPhone());
                result.put("contact", userAddress.getContact());
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
    }

    private final String SHOPHOMETEMPLATES_CACHE_KEY = "shopHomeTemplates";

    // 获取产品详情
    @RequestMapping("/template/getList")
    @ResponseBody
    @RequestLog
    public Map<String, Object> getTemplate(HttpServletRequest request) {
        Map<String, Object> map = CommonUtils.successResponse();
        JSONArray result = new JSONArray();
        if (cacheManagerUtil.isExist(SHOPHOMETEMPLATES_CACHE_KEY)) {
            String cacheValue = cacheManagerUtil.jGet(SHOPHOMETEMPLATES_CACHE_KEY);
            if (!StringUtils.isEmpty(cacheValue)) {
                try {
                    result = JSONArray.parseArray(cacheValue);
                    map.put(RETURN_CODE, 0);
                    map.put(RETURN_DATA, result);
                    return map;
                } catch (Exception e) {
                    logger.error("e = " + e.getMessage());
                }
            }
        }

        logger.info("首页没有缓存,读取数据库");
        List<ShopHomeTemplateVo> shopHomeTemplates = shopHomeTemplateVoService.getHomeTemplateByAll();
        if (shopHomeTemplates != null) {
            map.put(RETURN_CODE, 0);
            result = JSONArray.parseArray(new org.json.JSONArray(shopHomeTemplates).toString());

            cacheManagerUtil.jSet(SHOPHOMETEMPLATES_CACHE_KEY, new org.json.JSONArray(shopHomeTemplates).toString(),
                    CacheManagerUtil.SHOW_VALID_TIME);
            map.put(RETURN_DATA, result);
            return map;
        }

        map.put(RETURN_CODE, ResponseCodeHelper.NO_TEMPLATES);
        map.put("msg", "没有这条数据");
        return map;
    }

}